package com.hyjx.framework.common.util;

import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.FieldMergingArgs;
import com.aspose.words.IFieldMergingCallback;
import com.aspose.words.IMailMergeDataSource;
import com.aspose.words.ImageFieldMergingArgs;
import com.aspose.words.License;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class WordUtil {
    static {
        try {
            License license = new License();
            license.setLicense(new ByteArrayInputStream("<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>21991231</LicenseExpiry><SerialNumber>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature></License>".getBytes()));
        } catch (Exception e) {
            System.out.println("aspose授权失败!");
        }
    }

    private Document doc;

    public WordUtil(InputStream template) throws Exception {
        doc = new Document(template);
    }

    public void mergeMap(Map<String, Object> dataMap) throws Exception {
        //回调函数
        doc.getMailMerge().setFieldMergingCallback(new IFieldMergingCallback() {
            private String fieldName = null;
            private Object fieldValue = null;
            private DocumentBuilder builder = null;

            public void fieldMerging(FieldMergingArgs fma) throws Exception {
                fieldName = fma.getFieldName();
                fieldValue = fma.getFieldValue();
                builder = new DocumentBuilder(fma.getDocument());
                builder.moveToMergeField(fieldName);
                builder.insertHtml((String) fieldValue);
            }

            public void imageFieldMerging(ImageFieldMergingArgs arg0) throws Exception {

            }

        });
        List<String> names = new ArrayList<String>();
        List<Object> values = new ArrayList<Object>();
        String tmp_key;
        for (Iterator<String> it = dataMap.keySet().iterator(); it.hasNext(); ) {
            tmp_key = it.next();
            if (!(dataMap.get(tmp_key) instanceof List)) {
                names.add(tmp_key);
                values.add(dataMap.get(tmp_key));
                it.remove();
            }
        }
        doc.getMailMerge().execute((String[]) names.toArray(new String[names.size()]), values.toArray());
        for (String key : dataMap.keySet()) {
            doc.getMailMerge().executeWithRegions(new MailMergeDataSource(key, (List) dataMap.get(key)));
        }
    }
}

class MailMergeDataSource implements IMailMergeDataSource {
    private List<Map<String, Object>> dataList;
    private Map<String, Object> curMap = null;
    private String tableName;
    private int index = -1;

    public MailMergeDataSource(String tableName, List<Map<String, Object>> dataList) {
        this.dataList = dataList;
        this.tableName = tableName;
    }

    public String getTableName() throws Exception {
        return this.tableName;
    }

    public boolean moveNext() throws Exception {
        index++;
        if (this.dataList != null && this.dataList.size() > index) {
            this.curMap = dataList.get(index);
            return true;
        }
        return false;
    }

    public boolean getValue(String key, Object[] objs) throws Exception {
        if (curMap != null && objs != null && objs.length > 0) {
            objs[0] = curMap.get(key);
            return true;
        }
        return false;
    }

    @SuppressWarnings("unchecked")
    public IMailMergeDataSource getChildDataSource(String tableName) throws Exception {
        return new MailMergeDataSource(tableName, (List) curMap.get(tableName));
    }
}
